<?php
//$client = new swoole_redis;
//$client->connect('127.0.0.1', 6379, function (swoole_redis $client, $result) {
//    if ($result === false) {
//        echo "connect to redis server failed.\n";
//        return;
//    }
//    $client->set('key', 'swoole', function (swoole_redis $client, $result) {
//        var_dump($result);
//    });
//});

/**
 * 异步redis
 * @Author   Wcj
 * @DateTime 2019/3/14 17:38
 */
class AsyncRedis
{
    // redis实例
    private $redis = null;

    const HOST = '127.0.0.1';
    const PORT = 6379;

    public function __construct()
    {
        $this->redis = new swoole_redis;
        $this->redis->on('close', [$this, 'onClose']);
        $this->redis->on('message', [$this, 'onMessage']);
//        $this->redis->set([
//            'timeout' => 1.5,
//            'password' => 1.5,
//            'database' => 0,
//        ]);
    }

    /**
     * 连接redis并执行
     * @Author   Wcj
     * @DateTime 2019/3/14 18:14
     */
    public function exec()
    {
        $this->redis->connect(self::HOST, self::PORT, function (swoole_redis $client, $result) {
            if ($result === false) {
                echo "connect to redis server failed.\n";
                return;
            }

            // 设置键值对
            $client->set('key-' . mt_rand(1, 1000), 'swoole', function (swoole_redis $client, $result) {
                echo $this->setMsg(print_r($result, true));

                // 关闭连接
                $client->close();
            });

            // 获取所有key
            $client->keys('*', function (swoole_redis $client, $result) {
                echo $this->setMsg(print_r($result, true));

                // 关闭连接
                $client->close();
            });
        });

        return true;
    }

    /**
     * 接收订阅消息
     * @Author   Wcj
     * @DateTime 2019/3/15 14:18
     * @param swoole_redis $redis
     * @param array $message
     */
    public function onMessage(swoole_redis $redis, array $message)
    {
        echo $this->setMsg('接收到消息：' . print_r($message, true));
//        $redis->publish(['chat' => '啦啦啦德玛西亚']);
    }

    /**
     * 方法名
     * @Author   Wcj
     * @DateTime 2019/3/15 14:18
     * @param swoole_redis $redis
     */
    public function onClose(swoole_redis $redis)
    {
        $this->setMsg('关闭连接');
    }

    /**
     * 设置消息
     * @Author   Wcj
     * @DateTime 2019/3/14 15:22
     * @param $msg
     * @return string
     */
    public function setMsg($msg)
    {
        return $msg . PHP_EOL;
    }
}

$asyncRedis = new AsyncRedis();
$asyncRedis->exec();
echo '代码语句';


